import Https from "@/utils/Https";
import { ActionType, ProTable } from "@ant-design/pro-components";
import { Alert, Form, Input, message, Modal } from "antd";
import { FC, useEffect, useRef, useState } from "react";

const BatchSign: FC<any> = (props) => {
  const { selectedRowKeys, onSuccess, open, onClose } = props;
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [editForm] = Form.useForm();
  const [messageStatus, setMessageStatus] = useState("");
  const [messageText, setMessageText] = useState("");
  //获取批量签到数据
  const getBatchList = async () => {
    setLoading(true);
    let res: any = await Https.post(
      "/course/sched/listByBookRecordIds",
      selectedRowKeys,
      true
    );
    setLoading(false);
    if (res.code == 200 && res.data) {
      let objList = [];
      let ids = [];
      res.data.map((item) => {
        ids.push(item.bookRecordId);
        objList.push({ ...item, id: item.bookRecordId, code: item.classCode });
      });
      setEditableRowKeys(ids);
      setDataList(objList);
    } else {
      setDataList([]);
      message.error(res.msg);
    }
  };
  //批量签到
  const handleOk = async () => {
    let result = await editForm.validateFields(); // 调用表单验证
    let objList = [];
    dataList.map((item) => {
      objList.push({
        bookRecordId: item.id,
        classCode: result[item.id].code.toUpperCase(),
      });
    });
    setLoading(true);
    let res = await Https.post("/course/sched/batchSignIn", objList, true);
    setLoading(false);
    setMessageText(res.msg);
    editForm.resetFields();
    getBatchList();
    onSuccess();
    if (res.code == 200) {
      setMessageStatus("success");
    } else {
      setMessageStatus("error");
    }
  };
  const operateThree = [
    {
      title: "用户信息",
      dataIndex: "id",
      hideInSearch: true,
      width: 300,
      editable: false,
      render: (text, record) => {
        return (
          <div style={{ marginLeft: "10px" }}>
            <span>{record.wechatUserName}</span>
            <span style={{ marginLeft: "2px", color: "#999999" }}>
              ({record.wechatUserPhone})
            </span>
          </div>
        );
      },
    },
    {
      title: "签到状态",
      dataIndex: "signinFlag",
      editable: false,
      valueEnum: {
        "1": { text: "已签到", status: "Success" },
        "0": { text: "未签到", status: "Default" },
      },
    },
    {
      title: "签到码",
      dataIndex: "code",
      editable: true,
      renderFormItem: (_, { isEditable }) => {
        return (
          isEditable && (
            <Input
              placeholder="请输入签到码"
              maxLength={6}
              allowClear
              showCount
            />
          )
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: "此项为必填项",
          },
          {
            pattern: /^[0-9]{6}$/,
            message: "请输入6位数字",
          },
        ],
      },
      //render: (_, record) => record.code,
    },
    {
      title: "操作",
      fixed: "right",
      dataIndex: "operator",
      align: "center",
      width: 100,
      editable: false,
      render: (_, record, index) => {
        return (
          index > 0 && (
            <a
              onClick={() => {
                let objList = [...dataList];
                objList.splice(index, 1);
                setDataList([...objList]);
              }}
            >
              删除
            </a>
          )
        );
      },
    },
  ];
  useEffect(() => {
    if (open && selectedRowKeys.length > 0) {
      editForm.resetFields();
      getBatchList();
    }
  }, [open, selectedRowKeys]);
  return (
    <Modal
      title="批量签到"
      open={open}
      width="60%"
      confirmLoading={loading}
      onOk={() => {
        handleOk();
      }}
      onCancel={() => {
        onClose();
      }}
    >
      {messageStatus == "success" && (
        <Alert message={messageText} type="success" showIcon />
      )}
      {messageStatus == "error" && (
        <Alert message={messageText} type="error" showIcon />
      )}
      <ProTable
        key="tableTwo"
        style={{ margin: "24px 0" }}
        columns={operateThree}
        rowKey="id"
        actionRef={actionRef}
        loading={loading}
        dataSource={dataList}
        search={false}
        options={false}
        pagination={false}
        editable={{
          type: "multiple",
          form: editForm,
          editableKeys,
        }}
        scroll={{ y: 300 }}
      />
    </Modal>
  );
};
export default BatchSign;
